//
//  XJOrderDetailViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/5/28.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  订单详情

#import "XJOrderDetailViewController.h"
//Controller
#import "XJPayViewController.h"
#import "XJAfterSaleViewController.h"
#import "XJCommentViewController.h"


//view
#import "XJMyOrderCell.h"
#import "XJOrderDetailHeaderView.h"
#import "XJOrderDescribeCell.h"
#import "XJOrderDetailBottomView.h" //底部view

#import "XJOrderDetailCell1.h"
#import "XJOrderDetailCell2.h"
#import "XJOrderDetailCell3.h"
#import "XJOrderDetailCell4.h"

//model
#import "XJOrderDetailBigModel.h"
#import "XJOrderDetailCell1Model.h"
#import "XJOrderDetailAddressModel.h"
#import "XJMyOrderBtnModel.h"


@interface XJOrderDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) XJOrderDetailHeaderView *headerView;//表头
@property(nonatomic, strong) XJOrderDetailBottomView *bottomView;//底部view
/**标记 很多可用数据*/
@property(nonatomic, strong) XJOrderDetailBigModel *bigModel;
/**标记 第一个cell 的数据*/
@property (nonatomic, strong) XJOrderDetailCell1Model *cell1Model;
/**标记 标记表头地址数据*/
@property (nonatomic, strong) XJOrderDetailAddressModel *addressModel;

@end

@implementation XJOrderDetailViewController
#pragma mark - 一 lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight - XJBottomTabH) style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        
        _tableView.rowHeight = 120;
        

        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [_tableView registerNib:[UINib nibWithNibName:@"XJOrderDetailCell1" bundle:nil] forCellReuseIdentifier:@"XJOrderDetailCell1"];
        [_tableView registerNib:[UINib nibWithNibName:@"XJOrderDetailCell2" bundle:nil] forCellReuseIdentifier:@"XJOrderDetailCell2"];
        [_tableView registerNib:[UINib nibWithNibName:@"XJOrderDetailCell3" bundle:nil] forCellReuseIdentifier:@"XJOrderDetailCell3"];
        [_tableView registerNib:[UINib nibWithNibName:@"XJOrderDetailCell4" bundle:nil] forCellReuseIdentifier:@"XJOrderDetailCell4"];
        
    }
    return _tableView;
}

- (XJOrderDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[XJOrderDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 180)]; // h:160
    }
    return _headerView;
}
- (XJOrderDetailBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView =[[XJOrderDetailBottomView alloc] initWithFrame:CGRectMake(0, KHeight - XJTopNavH  - 50 - 10, KWidth, 50)];
        
        XJWeakSelf(self);
        _bottomView.firstButtonBlock = ^(XJMyOrderBtnModel *btnModel) {
            [weakself firstButtonBusindessLogicWithButtonModel:btnModel];
        };
        
        _bottomView.secondButtonBlock = ^(XJMyOrderBtnModel *btnModel) {
            
            [weakself secondButtonBusindessLogicWithButtonModel:btnModel];
            XJLog(@"点击第二个按钮:%@",btnModel);
        };
    }
    return _bottomView;
}

#pragma mark - 二 view & UI
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestDetailData];
    
    [self setupView];
}

- (void)setupView {
    self.navigationItem.title = @"订单详情";
    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    
    
    [self.view addSubview:self.bottomView];
    
    // 配置底部view按钮的状态
    [self congigureBottomButtonTitle];
    
}

// 被底部视图的两个按钮标题赋值
- (void)congigureBottomButtonTitle {
    NSString *firstStr = @"取消订单";
    NSString *secondStr = @"立即付款";
    
    
    switch (self.orderDetailType) {
        case XJOrderDetailTypeWaitPay:
        {
            firstStr = @"取消订单";
            secondStr = @"立即付款";
        }break;
        case XJOrderDetailTypeWatiReceive:{
            firstStr = @"申请售后";
            secondStr = @"确认收货";
        }break;
        case XJOrderDetailTypeWaitEvaluate:{
            firstStr = @"申请售后";
            secondStr = @"去评价";
        }break;
        case XJOrderDetailTypeFinish:{
            firstStr = @"删除订单";
            secondStr = @"申请售后";
        }break;
        
        default:
            break;
    }
    
    [self.bottomView configureOrderDetailBottomViewHideFirstBtn:NO FistTitle:firstStr secondTitle:secondStr];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}


#pragma mark - 三 UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 2;
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 4;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 
    if (indexPath.row == 0) {
        
        XJOrderDetailCell1 *cell1 = [tableView dequeueReusableCellWithIdentifier:@"XJOrderDetailCell1"];
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell1.cell1Model = self.cell1Model;
        
        return cell1;
        
    }else if (indexPath.row == 1){
        
        XJOrderDetailCell2 *cell2 = [tableView dequeueReusableCellWithIdentifier:@"XJOrderDetailCell2"];
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell2.model = self.bigModel;
        return cell2;
        
    }else if (indexPath.row == 2) {
        
        XJOrderDetailCell3 *cell3 = [tableView dequeueReusableCellWithIdentifier:@"XJOrderDetailCell3"];
        cell3.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell3.model = self.bigModel;
        
        return cell3;

    }else {
        
        XJOrderDetailCell4 *cell4 = [tableView dequeueReusableCellWithIdentifier:@"XJOrderDetailCell4"];
        cell4.selectionStyle = UITableViewCellSelectionStyleNone;

        cell4.model = self.bigModel;
        return cell4;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 3) {
        return 65;
    }else {
        return 80;
    }
}

#pragma mark - 四 网络请求
- (void)requestDetailData {
    
    
    [XJHttpTool requestOrderDetailWithOrderSN:self.orderSN successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if([code isEqualToString:@"0"]){
            NSDictionary *orderDic = responseObjc[@"data"][@"order"];
            
            self.bigModel = [XJOrderDetailBigModel mj_objectWithKeyValues:orderDic];
            self.addressModel = [XJOrderDetailAddressModel mj_objectWithKeyValues:orderDic[@"order_address"]];
            
            //头部信息
            NSArray *goodsArr = orderDic[@"goods"];
            NSDictionary *goodDic = [goodsArr firstObject];
            self.cell1Model = [XJOrderDetailCell1Model mj_objectWithKeyValues:goodDic];
            
            
            //最下面 按钮模型 数组
            NSArray *btnsArr = orderDic[@"btns"];
            XJLog(@"%@",orderDic[@"btns"]);
            NSMutableArray *tempBtnArr = [NSMutableArray array];
            
            for (NSDictionary *btnDic in btnsArr) {
                XJMyOrderBtnModel *btnM = [XJMyOrderBtnModel mj_objectWithKeyValues:btnDic];
                [tempBtnArr addObject:btnM];
            }
            
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                
                //给表头赋值
                [self.headerView configureOrderDetailHeaderViewWithMatter:self.bigModel.state_name name:self.addressModel.name phone:self.addressModel.phone addres:self.addressModel.address];
                
                //给最下面的按钮赋值
                [self.bottomView configureOrderDetailBottomViewWithButtonArray:tempBtnArr.copy];
            });
        }
    } failH:^(NSError *error) {
      
        [JRToast showWithText:[error localizedDescription]];
    }];
}
/**
 {
 "code": 0,
 "data": {
 "order": {
 "id": 389,
 "shop_id": 11,
 "order_sn": "SN18062110480500000036",
 "order_state": 1,
 "address_id": 396,
 "customer_id": 7,
 "comment": "",
 "order_amount": 21.0,
 "goods_amount": 21.0,
 "express_amount": 0.0,
 "express_type": 2,
 "create_time": 1529549285373,
 "state_name": "待付款",
 "shop_name": "小何店铺",
 "goods": [{
 "id": 402,
 "order_id": 389,
 "goods_id": 140,
 "price": 21.0,
 "option_id": 131,
 "quantity": 1,
 "option_name": "鸿+小",
 "amount": 21.0,
 "goods_name": "iOS测试商品1",
 "cover": "http://static.zertone1.com/c3QNDIRqqim9m3zhtRqpSquiAoTnuH25.png",
 "stock": 36,
 "option_stock": 19
 }],
 "order_address": {
 "id": 396,
 "name": "哈哈",
 "phone": "15837694444",
 "address": "浙江省杭州市滨江区华盛达广场110",
 "province_id": 0,
 "city_id": 0,
 "district_id": 0,
 "province": "浙江省",
 "city": "杭州市",
 "district": "滨江区",
 "lng": 120.18816586,
 "lat": 30.19434525
 },
 "customer": {
 "uuid": "25310990",
 "nickname": "都纷纷",
 "phone": "15837694444",
 "avatar": "http://static.zertone1.com/upload/avatar/2018_03_23/acf3afd39f2d4f44b7f00909e70d5297.jpg"
 },
 "shop_address": "无",
 "btns": [{
 "code": "pay",
 "text": "立即付款",
 "text_color": "000000",
 "background_color": "FFDA44"
 }, {
 "code": "cancel",
 "text": "取消订单",
 "text_color": "000000",
 "background_color": "FFFFFF"
 }]
 }
 }
 }
 */




//取消订单网络请求
- (void)requestCancelOrder{
    
    
    [XJHttpTool requestOrderCancelOrderWithOrderNum:self.bigModel.order_sn successH:^(id responseObjc) {
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            XJLog(@"取消订单成功");
//
            //如果是取消订单就刷新一下页面 ,如果是删除订单 成功之后的逻辑应该是:返回到上一级页面
            [self requestDetailData];
            
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}

//删除订单网络请求
- (void)requestDeleteOrder {
    
    
    [XJHttpTool requestOrderDeleteOrderWithOrderSN:self.bigModel.order_sn successH:^(id responseObjc) {
        XJLog(@"删除成功:%@",responseObjc);
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            //返回到上一界面
            [self.navigationController popViewControllerAnimated:YES];
            
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        
        [JRToast showWithText:[error localizedDescription]];
        
    }];
}
//确认收货
- (void)requestReceive {
    [XJHttpTool requestOrderReceiveWithOrderSN:self.bigModel.order_sn successH:^(id responseObjc) {

        [self.navigationController popViewControllerAnimated:YES];
        
    } failH:^(NSError *error) {
        
    }];
}


#pragma mark - 让tableView的sectionHeader 随cell一起移动
//https://www.jianshu.com/p/264bd4d33c7f
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (self.tableView == scrollView) {
        CGFloat sectionHeaderHeight =  40;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}


#pragma mark - 五 最下面按钮 业务逻辑
- (void)firstButtonBusindessLogicWithButtonModel:(XJMyOrderBtnModel *)btnModel {
    XJLog(@"第一个按钮:%@",btnModel);
    if ([btnModel.code isEqualToString:kOrderBtnPay]) {
        XJLog(@"立即付款");
        XJPayViewController *payVC = [[XJPayViewController alloc] init];
        
        // 请求参数
        
        payVC.foreign_infos = self.bigModel.order_sn;
        payVC.order_amount = self.bigModel.order_amount;
        payVC.order_type = @"2";
        
        [self.navigationController pushViewController:payVC animated:YES];
    }else if ([btnModel.code isEqualToString:kOrderBtnRefund]) {
        XJLog(@"申请售后");
        
        XJAfterSaleViewController *afterSaleVC = [[XJAfterSaleViewController alloc] init];
        afterSaleVC.order_goods_id = self.bigModel.orderId;
        afterSaleVC.orderSN = self.bigModel.order_sn;
        [self.navigationController pushViewController:afterSaleVC animated:YES];
    }else {
        XJLog(@"%@",btnModel);
    }
}

- (void)secondButtonBusindessLogicWithButtonModel:(XJMyOrderBtnModel *)btnModel {
    if ([btnModel.code isEqualToString:kOrderBtnCancel]) {
        
        XJLog(@"取消订单");
        [self requestCancelOrder];
        
    }else if ([btnModel.code isEqualToString:kOrderBtnReceive]){
        
        XJLog(@"确认收货");
        [self requestReceive];
        
    }else if([btnModel.code isEqualToString:kOrderBtnDelete]){
        
        XJLog(@"删除订单");
        
        [self requestDeleteOrder];
        
    }else if ([btnModel.code isEqualToString:kOrderBtnComment]){
        
        XJLog(@"立即评价");
        XJCommentViewController *commentVC = [[XJCommentViewController alloc] init];
        commentVC.order_goods_id = self.bigModel.orderId;
        commentVC.orderSN = self.bigModel.order_sn;
        
        [self.navigationController pushViewController:commentVC animated:YES];
        
    }else {
        
        XJLog(@"%@",btnModel);
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
